//
//  NGForumSearchNavigationBarView.swift
//  NingguoForum
//
//  Created by zhengsw on 2025/8/8.
//  Copyright © 2025 zhengsw. All rights reserved.
//


import UIKit
import RxSwift
import SnapKit

// MARK: - Protocol
public protocol NGForumSearchNavigationBarViewDelegate: AnyObject {
    func goUserInfoAction()
    func searchAction(text: String)
}

// MARK: - Main Class
class NGForumSearchNavigationBarView: UIView {
    
    // MARK: - Properties
    weak var delegate: NGForumSearchNavigationBarViewDelegate?
    private let disposeBag = DisposeBag()
    
    // MARK: - UI Components
    private lazy var userButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "home_back"), for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.accessibilityLabel = "返回"
        return button
    }()
    
    private lazy var searchTextField: UITextField = {
        let textField = UITextField()
        textField.backgroundColor = RGB_COLOR(r: 248, g: 248, b: 248)
        textField.layer.cornerRadius = 10
        textField.layer.masksToBounds = true
        
        // 设置placeholder样式
        let placeholderAttributes: [NSAttributedString.Key: Any] = [
            .foregroundColor: UIColor.systemGray,
            .font: UIFont.systemFont(ofSize: 14)
        ]
        textField.attributedPlaceholder = NSAttributedString(
            string: "搜索",
            attributes: placeholderAttributes
        )
        
        // 设置搜索图标
        setupSearchIcon(for: textField)
        
        // 设置键盘属性
        textField.returnKeyType = .search
        textField.keyboardType = .default
        textField.clearButtonMode = .whileEditing
        textField.autocorrectionType = .no
        textField.autocapitalizationType = .none
        
        return textField
    }()
    
    private lazy var editButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "edit"), for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.accessibilityLabel = "编辑"
        return button
    }()
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupBindings()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
        setupBindings()
    }
    
    // MARK: - Setup Methods
    private func setupUI() {
        backgroundColor = .white
        
        addSubview(userButton)
        addSubview(searchTextField)
        addSubview(editButton)
        
        setupConstraints()
    }
    
    private func setupConstraints() {
        userButton.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 44, height: 44))
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview().offset(KDevice_StatusBar_Height)
        }
        
        editButton.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 44, height: 44))
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(KDevice_StatusBar_Height)
        }
        
        searchTextField.snp.makeConstraints { make in
            make.centerY.equalTo(userButton)
            make.left.equalTo(userButton.snp.right).offset(20)
            make.right.equalTo(editButton.snp.left).offset(-20)
            make.height.equalTo(34)
        }
    }
    
    private func setupSearchIcon(for textField: UITextField) {
        let searchIcon = UIImageView(image: UIImage(named: "edit"))
        searchIcon.tintColor = UIColor.systemGray
        searchIcon.contentMode = .scaleAspectFit
        
        let iconContainer = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 30))
        searchIcon.frame = CGRect(x: 8, y: 0, width: 30, height: 30)
        iconContainer.addSubview(searchIcon)
        
        textField.leftView = iconContainer
        textField.leftViewMode = .always
    }
    
    private func setupBindings() {
        // 用户按钮点击
        userButton.rx.tap
            .subscribe(onNext: { [weak self] in
                self?.handleUserButtonTap()
            })
            .disposed(by: disposeBag)
        
        // 编辑按钮点击
        editButton.rx.tap
            .subscribe(onNext: { [weak self] in
                self?.handleEditButtonTap()
            })
            .disposed(by: disposeBag)
        
        // 搜索框文本变化（防抖）
        searchTextField.rx.text
            .orEmpty
            .debounce(.milliseconds(300), scheduler: MainScheduler.instance)
            .distinctUntilChanged()
            .subscribe(onNext: { [weak self] text in
                self?.handleSearchTextChange(text)
            })
            .disposed(by: disposeBag)
        
        // 搜索框焦点变化
        searchTextField.rx.controlEvent(.editingDidBegin)
            .subscribe(onNext: { [weak self] in
                self?.handleSearchBegin()
            })
            .disposed(by: disposeBag)
        
        searchTextField.rx.controlEvent(.editingDidEnd)
            .subscribe(onNext: { [weak self] in
                self?.handleSearchEnd()
            })
            .disposed(by: disposeBag)
        
        // 搜索框返回键
        searchTextField.rx.controlEvent(.editingDidEndOnExit)
            .subscribe(onNext: { [weak self] in
                self?.handleSearchSubmit()
            })
            .disposed(by: disposeBag)
    }
    
    // MARK: - Action Handlers
    private func handleUserButtonTap() {
        delegate?.goUserInfoAction()
    }
    
    private func handleEditButtonTap() {
        print("跳登录")
        // 这里可以添加具体的登录逻辑
    }
    
    private func handleSearchTextChange(_ text: String) {
        // 可以在这里添加实时搜索逻辑
        print("搜索文本变化: \(text)")
    }
    
    private func handleSearchBegin() {
        print("开始编辑搜索框")
    }
    
    private func handleSearchEnd() {
        print("结束编辑搜索框")
    }
    
    private func handleSearchSubmit() {
        guard let searchText = searchTextField.text, !searchText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
            return
        }
        
        delegate?.searchAction(text: searchText.trimmingCharacters(in: .whitespacesAndNewlines))
        searchTextField.resignFirstResponder()
        clearSearchText()
    }
    
    func clearSearchText() {
        searchTextField.text = ""
    }
}

// MARK: - UITextFieldDelegate (如果需要的话)
extension NGForumSearchNavigationBarView: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        handleSearchSubmit()
        return true
    }
    
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        // 清除时触发搜索
        delegate?.searchAction(text: "")
        return true
    }
}

